/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy-layui
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy-layui
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.modular.dishpackage.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import vip.xiaonuo.core.consts.CommonConstant;
import vip.xiaonuo.core.consts.SymbolConstant;
import vip.xiaonuo.core.context.login.LoginContextHolder;
import vip.xiaonuo.core.enums.CommonStatusEnum;
import vip.xiaonuo.core.exception.PermissionException;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.exception.enums.PermissionExceptionEnum;
import vip.xiaonuo.core.factory.PageFactory;
import vip.xiaonuo.core.factory.TreeBuildFactory;
import vip.xiaonuo.core.pojo.node.CommonBaseTreeNode;
import vip.xiaonuo.core.pojo.page.PageResult;
import vip.xiaonuo.modular.dishpackage.entity.DishPackage;
import vip.xiaonuo.modular.dishpackage.enums.DishPackageExceptionEnum;
import vip.xiaonuo.modular.dishpackage.mapper.DishPackageMapper;
import vip.xiaonuo.modular.dishpackage.param.DishPackageParam;
import vip.xiaonuo.modular.dishpackage.service.DishPackageService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.sys.modular.auth.service.AuthService;
import vip.xiaonuo.sys.modular.role.enums.SysRoleDataScopeTypeEnum;


import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

/**
 * 菜品/套餐service接口实现类
 *
 * @author SunRui
 * @date 2022-02-11 11:54:42
 */
@Service
public class DishPackageServiceImpl extends ServiceImpl<DishPackageMapper, DishPackage> implements DishPackageService {

    @Resource
    private AuthService authService;
    @Override
    public PageResult<DishPackage> page(DishPackageParam dishPackageParam) {
        QueryWrapper<DishPackage> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(dishPackageParam)) {

            // 根据机构名称模糊查询
            if (ObjectUtil.isNotEmpty(dishPackageParam.getName())) {
                queryWrapper.lambda().like(DishPackage::getName, dishPackageParam.getName());
            }

            // 根据机构id查询
            if (ObjectUtil.isNotEmpty(dishPackageParam.getId())) {
                queryWrapper.lambda().eq(DishPackage::getId, dishPackageParam.getId());
            }

            // 根据父机构id查询
            if (ObjectUtil.isNotEmpty(dishPackageParam.getPid())) {
                queryWrapper.lambda().and(i-> i.eq(DishPackage::getId, dishPackageParam.getPid())
                        .or()
                        .like(DishPackage::getPids, dishPackageParam.getPid()));

            }
            //排序
            if(ObjectUtil.isAllNotEmpty(dishPackageParam.getSortBy(), dishPackageParam.getOrderBy())) {
                queryWrapper.orderBy(true, dishPackageParam.getOrderBy().equals(CommonConstant.ASC), StrUtil.toUnderlineCase(dishPackageParam.getSortBy()));
            } else {
                //根据排序升序排列，序号越小越在前
                queryWrapper.lambda().orderByAsc(DishPackage::getSort);
            }
        }

//        boolean superAdmin = LoginContextHolder.me().isSuperAdmin();
//
//        // 如果是超级管理员则获取所有组织机构，否则只获取其数据范围的机构数据
//        if (!superAdmin) {
//            List<Long> dataScope = dishPackageParam.getDataScope();
//            if (ObjectUtil.isEmpty(dataScope)) {
//                return new PageResult<>(new Page<>());
//            } else {
//                Set<Long> dataScopeSet = CollectionUtil.newHashSet(dataScope);
//                dataScope.forEach(orgId -> {
//                    //此处获取所有的上级节点，放入set，用于构造完整树
//                    List<Long> parentAndChildIdListWithSelf = this.getParentIdListById(orgId);
//                    dataScopeSet.addAll(parentAndChildIdListWithSelf);
//                });
//                queryWrapper.lambda().in(DishPackage::getId, dataScopeSet);
//            }
//        }
        // 查询启用状态的
        queryWrapper.lambda().eq(DishPackage::getStatus, CommonStatusEnum.ENABLE.getCode());
        return new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));
    }

    @Override
    public List<DishPackage> list(DishPackageParam dishPackageParam) {
        LambdaQueryWrapper<DishPackage> queryWrapper = new LambdaQueryWrapper<>();
        if (ObjectUtil.isNotNull(dishPackageParam)) {
            //根据父机构id查询
            if (ObjectUtil.isNotEmpty(dishPackageParam.getPid())) {
                queryWrapper.eq(DishPackage::getPid, dishPackageParam.getPid());
            }
        }
//        //如果是超级管理员则获取所有组织机构，否则只获取其数据范围的机构数据
//        boolean superAdmin = LoginContextHolder.me().isSuperAdmin();
//        if (!superAdmin) {
//            List<Long> dataScope = dishPackageParam.getDataScope();
//            if (ObjectUtil.isEmpty(dataScope)) {
//                return CollectionUtil.newArrayList();
//            } else {
//                Set<Long> dataScopeSet = CollectionUtil.newHashSet(dataScope);
//                dataScope.forEach(orgId -> {
//                    //此处获取所有的上级节点，放入set，用于构造完整树
//                    List<Long> parentAndChildIdListWithSelf = this.getParentIdListById(orgId);
//                    dataScopeSet.addAll(parentAndChildIdListWithSelf);
//                });
//                queryWrapper.in(DishPackage::getId, dataScopeSet);
//            }
//        }
        queryWrapper.eq(DishPackage::getStatus, CommonStatusEnum.ENABLE.getCode());
        //根据排序升序排列，序号越小越在前
        queryWrapper.orderByAsc(DishPackage::getSort);
        return this.list(queryWrapper);
    }

    @Override
    public void add(DishPackageParam dishPackageParam) {
        //校验参数，检查是否存在相同的名称和编码
        checkParam(dishPackageParam, false);
        //获取父id
        Long pid = dishPackageParam.getPid();
        System.out.println("父id:"+dishPackageParam.getPid());

        DishPackage dishPackage = new DishPackage();
        BeanUtil.copyProperties(dishPackageParam, dishPackage);
        this.fillPids(dishPackage);
        dishPackage.setStatus(CommonStatusEnum.ENABLE.getCode());
        this.save(dishPackage);




//        this.authService.refreshUserDataScope(dishPackage.getId());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<DishPackageParam> dishPackageParamList) {
        dishPackageParamList.forEach(dishPackageParam -> {
            DishPackage dishPackage = this.queryDishPackage(dishPackageParam);
            Long id = dishPackage.getId();
            boolean superAdmin = LoginContextHolder.me().isSuperAdmin();
            if (!superAdmin) {
                List<Long> dataScope = LoginContextHolder.me().getLoginUserDataScopeIdList();
                //数据范围为空
                if (ObjectUtil.isEmpty(dataScope)) {
                    throw new PermissionException(PermissionExceptionEnum.NO_PERMISSION_OPERATE);
                } else if (!dataScope.contains(id)) {
                    //所操作的数据不在自己的数据范围内
                    throw new PermissionException(PermissionExceptionEnum.NO_PERMISSION_OPERATE);
                }
            }

            // 查询子节点
            List<Long> childIdList = this.getChildIdListById(id);
            childIdList.add(id);



            LambdaUpdateWrapper<DishPackage> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.in(DishPackage::getId, childIdList)
                    .set(DishPackage::getStatus, CommonStatusEnum.DELETED.getCode());
            this.update(updateWrapper);

//            // 级联删除该机构及子机构对应的角色-数据范围关联信息
//            sysRoleDataScopeService.deleteRoleDataScopeListByOrgIdList(childIdList);
//
//            // 级联删除该机构子机构对应的用户-数据范围关联信息
//            sysUserDataScopeService.deleteUserDataScopeListByOrgIdList(childIdList);
        });
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(DishPackageParam dishPackageParam) {
        DishPackage dishPackage = this.queryDishPackage(dishPackageParam);
        Long id = dishPackage.getId();



        //校验参数，检查是否存在相同的名称和编码
        checkParam(dishPackageParam, true);

//        //如果名称有变化，则修改对应员工的机构相关信息
//        if (!dishPackage.getName().equals(dishPackageParam.getName())) {
//            sysEmpService.updateEmpOrgInfo(dishPackage.getId(), dishPackage.getName());
//        }

        BeanUtil.copyProperties(dishPackageParam, dishPackage);
        this.fillPids(dishPackage);

        //不能修改状态，用修改状态接口修改状态
        dishPackage.setStatus(null);
        this.updateById(dishPackage);
        //将所有子的父id进行更新
        List<Long> childIdListById = this.getChildIdListById(dishPackage.getId());
        childIdListById.forEach(subChildId -> {
            DishPackage child = this.getById(subChildId);
            DishPackageParam childParam = new DishPackageParam();
            BeanUtil.copyProperties(child, childParam);
            this.edit(childParam);
        });
    }

    @Override
    public DishPackage detail(DishPackageParam dishPackageParam) {
        return this.queryDishPackage(dishPackageParam);
    }

    @Override
    public List<CommonBaseTreeNode> tree(DishPackageParam dishPackageParam) {
        List<CommonBaseTreeNode> treeNodeList = CollectionUtil.newArrayList();
        LambdaQueryWrapper<DishPackage> queryWrapper = new LambdaQueryWrapper<>();
//        List<Long> dataScope = dishPackageParam.getFilltree();
//        Set<Long> dataScopeSet = CollectionUtil.newHashSet(dataScope);
//        dataScope.forEach(dishPackageId -> {
//            //此处获取所有的上级节点，放入set，用于构造完整树
//            List<Long> parentAndChildIdListWithSelf = this.getParentIdListById(dishPackageId);
//            dataScopeSet.addAll(parentAndChildIdListWithSelf);
//        queryWrapper.in(DishPackage::getId, dataScopeSet);});
//


        // 只查询未删除的
        queryWrapper.eq(DishPackage::getStatus, CommonStatusEnum.ENABLE.getCode());
        //根据排序升序排列，序号越小越在前
        queryWrapper.orderByAsc(DishPackage::getSort);
        this.list(queryWrapper).forEach(dishPackage -> {
            CommonBaseTreeNode orgTreeNode = new CommonBaseTreeNode();
            orgTreeNode.setId(dishPackage.getId());
            orgTreeNode.setParentId(dishPackage.getPid());
            orgTreeNode.setTitle(dishPackage.getName());
            orgTreeNode.setValue(String.valueOf(dishPackage.getId()));
            orgTreeNode.setWeight(dishPackage.getSort());
            treeNodeList.add(orgTreeNode);
        });

        return new TreeBuildFactory<CommonBaseTreeNode>().doTreeBuild(treeNodeList);
    }

    @Override
    public List<Long> getDataScopeListByDataScopeType(Integer dataScopeType, Long dishPackageId) {
        List<Long> resultList = CollectionUtil.newArrayList();

        if (ObjectUtil.isEmpty(dishPackageId)) {
            return CollectionUtil.newArrayList();
        }

        // 如果是范围类型是全部数据，则获取当前系统所有的组织架构id
        if (SysRoleDataScopeTypeEnum.ALL.getCode().equals(dataScopeType)) {
            resultList = this.getDishPackageIdAll();
        }
        // 如果范围类型是本部门及以下部门，则查询本节点和子节点集合，包含本节点
        else if (SysRoleDataScopeTypeEnum.DEPT_WITH_CHILD.getCode().equals(dataScopeType)) {
            resultList = this.getChildIdListWithSelfById(dishPackageId);
        }
        // 如果数据范围是本部门，不含子节点，则直接返回本部门
        else if (SysRoleDataScopeTypeEnum.DEPT.getCode().equals(dataScopeType)) {
            resultList.add(dishPackageId);
        }

        return resultList;
    }

    /**
     * 根据条件获取组织机构id集合
     *
     * @author xuyuxiang
     * @date 2020/4/5 18:35
     */
    private List<Long> getDishPackageIdAll() {
        List<Long> resultList = CollectionUtil.newArrayList();

        LambdaQueryWrapper<DishPackage> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(DishPackage::getStatus, CommonStatusEnum.ENABLE.getCode());

        this.list(queryWrapper).forEach(dishPackage -> resultList.add(dishPackage.getId()));
        return resultList;
    }

    /**
     * 校验参数，检查是否存在相同的名称和编码
     *
     * @author xuyuxiang
     * @date 2020/3/25 21:23
     */
    private void checkParam(DishPackageParam dishPackageParam, boolean isExcludeSelf) {
        Long id = dishPackageParam.getId();
        String name = dishPackageParam.getName();
        String code = dishPackageParam.getCode();
        Long pid = dishPackageParam.getPid();

        //如果父id不是根节点
        if (!pid.equals(0L)) {
            DishPackage pOrg = this.getById(pid);
            if (ObjectUtil.isNull(pOrg)) {
                //父机构不存在
                throw new ServiceException(DishPackageExceptionEnum.dishPackage_NOT_EXIST);
            }
        }

        // 如果是编辑，父id和自己的id不能一致
        if (isExcludeSelf) {
            if (dishPackageParam.getId().equals(dishPackageParam.getPid())) {
                throw new ServiceException(DishPackageExceptionEnum.ID_CANT_EQ_PID);
            }

            // 如果是编辑，父id不能为自己的子节点
            List<Long> childIdListById = this.getChildIdListById(dishPackageParam.getId());
            if(ObjectUtil.isNotEmpty(childIdListById)) {
                if(childIdListById.contains(dishPackageParam.getPid())) {
                    throw new ServiceException(DishPackageExceptionEnum.PID_CANT_EQ_CHILD_ID);
                }
            }
        }

        LambdaQueryWrapper<DishPackage> queryWrapperByName = new LambdaQueryWrapper<>();
        queryWrapperByName.eq(DishPackage::getName, name)
                .ne(DishPackage::getStatus, CommonStatusEnum.DELETED.getCode());

        LambdaQueryWrapper<DishPackage> queryWrapperByCode = new LambdaQueryWrapper<>();
        queryWrapperByCode.eq(DishPackage::getCode, code)
                .ne(DishPackage::getStatus, CommonStatusEnum.DELETED.getCode());

        if (isExcludeSelf) {
            queryWrapperByName.ne(DishPackage::getId, id);
            queryWrapperByCode.ne(DishPackage::getId, id);
        }
        int countByName = this.count(queryWrapperByName);
        int countByCode = this.count(queryWrapperByCode);

        if (countByName >= 1) {
            throw new ServiceException(DishPackageExceptionEnum.dishPackage_NAME_REPEAT);
        }
        if (countByCode >= 1) {
            throw new ServiceException(DishPackageExceptionEnum.dishPackage_CODE_REPEAT);
        }
    }

    /**
     * 获取联席管理
     *
     * @author SunRui
     * @date 2022-02-09 23:32:09
     */
    private DishPackage queryDishPackage(DishPackageParam dishPackageParam) {
        DishPackage dishPackage = this.getById(dishPackageParam.getId());
        if (ObjectUtil.isNull(dishPackage)) {
            throw new ServiceException(DishPackageExceptionEnum.dishPackage_NOT_EXIST);
        }
        return dishPackage;
    }

    private void fillPids(DishPackage dishPackage) {
        if (dishPackage.getPid().equals(0L)) {
            dishPackage.setPids(SymbolConstant.LEFT_SQUARE_BRACKETS +
                    0 +
                    SymbolConstant.RIGHT_SQUARE_BRACKETS +
                    SymbolConstant.COMMA);
        } else {
            //获取父组织机构
            DishPackage pDishPackage = this.getById(dishPackage.getPid());
            dishPackage.setPids(pDishPackage.getPids() +
                    SymbolConstant.LEFT_SQUARE_BRACKETS + pDishPackage.getId() +
                    SymbolConstant.RIGHT_SQUARE_BRACKETS +
                    SymbolConstant.COMMA);
        }
        System.out.println("pids:"+dishPackage.getPids());

    }

    /**
     * 根据节点id获取所有子节点id集合
     *
     * @author xuyuxiang
     * @date 2020/3/26 11:31
     */
    private List<Long> getChildIdListById(Long id) {
        List<Long> childIdList = CollectionUtil.newArrayList();
        LambdaQueryWrapper<DishPackage> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.like(DishPackage::getPids, SymbolConstant.LEFT_SQUARE_BRACKETS + id +
                SymbolConstant.RIGHT_SQUARE_BRACKETS);

        this.list(queryWrapper).forEach(dishPackage -> childIdList.add(dishPackage.getId()));

        return childIdList;
    }

    /**
     * 根据节点id获取所有父节点id集合，不包含自己
     *
     * @author xuyuxiang
     * @date 2020/4/6 14:53
     */
    private List<Long> getParentIdListById(Long id) {
        List<Long> resultList = CollectionUtil.newArrayList();
        DishPackage dishPackage = this.getById(id);
        String pids = dishPackage.getPids();
        String pidsWithRightSymbol = StrUtil.removeAll(pids, SymbolConstant.LEFT_SQUARE_BRACKETS);
        String pidsNormal = StrUtil.removeAll(pidsWithRightSymbol, SymbolConstant.RIGHT_SQUARE_BRACKETS);
        String[] pidsNormalArr = pidsNormal.split(SymbolConstant.COMMA);
        for (String pid : pidsNormalArr) {
            resultList.add(Convert.toLong(pid));
        }
        return resultList;
    }

    /**
     * 根据节点id获取所有子节点id集合，包含自己
     *
     * @author xuyuxiang
     * @date 2020/4/6 14:54
     */
    private List<Long> getChildIdListWithSelfById(Long id) {
        List<Long> childIdListById = this.getChildIdListById(id);
        List<Long> resultList = CollectionUtil.newArrayList(childIdListById);
        resultList.add(id);
        return resultList;
    }

    /**
     * 根据节点id获取父节点和子节点id集合，包含自己
     *
     * @author xuyuxiang
     * @date 2020/4/7 16:50
     */
    private List<Long> getParentAndChildIdListWithSelfById(Long id) {
        Set<Long> resultSet = CollectionUtil.newHashSet();
        List<Long> parentIdListById = this.getParentIdListById(id);
        List<Long> childIdListById = this.getChildIdListWithSelfById(id);
        resultSet.addAll(parentIdListById);
        resultSet.addAll(childIdListById);
        return CollectionUtil.newArrayList(resultSet);
    }
}
